package com.limh.gobang.service.resource

import android.text.TextUtils
import android.util.Log
import com.limh.gobang.bean.MsgEvent
import com.limh.gobang.service.utils.HttpContext
import com.limh.gobang.service.utils.StreamToolkit
import com.limh.gobang.utils.GsonUtils
import org.greenrobot.eventbus.EventBus
import java.io.OutputStreamWriter

/**
 * @function 对战数据处理
 * @author limh
 * @date 2018/5/4 13:34
 */
class ResourceFightHandler : IResourceUriHandler {

    private val TAG = "ResourceFightHandler"
    val suffix = "/fight"
    override fun accept(uri: String?): Boolean {
        return uri!!.startsWith(suffix)
    }

    override fun handle(uri: String?, httpContext: HttpContext?) {
        val ins = httpContext!!.underlySocket!!.getInputStream()
        var readLine = ""
        while (StreamToolkit.readContent(ins).apply { readLine = this!! } != null) {
            if (readLine == "") {
                Log.d(TAG, "header line finish")
                break
            }
            Log.d(TAG, "消息内容=$readLine")
            if (!TextUtils.isEmpty(readLine) && readLine != "\uFFFF") {
                val msg = GsonUtils.str2Bean(readLine, MsgEvent::class.java)
                EventBus.getDefault().post(msg)
            }

            val response = ""

            Log.i(TAG, "响应消息：$response")
            val osw = OutputStreamWriter(httpContext.underlySocket!!.getOutputStream(), Charsets.UTF_8)
            val sb = StringBuilder()
            sb.append("HTTP/1.1 200 OK\r\n")
            sb.append("Connection: keep-alive\r\n")
            sb.append("Content-length: ${response.toByteArray(Charsets.UTF_8).size}\r\n")
            sb.append("${StreamToolkit.addContentType("")}\r\n")
            sb.append("\r\n")
            sb.append("$response\r\n")
            osw.write(sb.toString())
            osw.flush()
            Log.d(TAG, "服务器响应了消息")
        }
    }
}